
package com.assistant.core.modules.sys.adapter.web.user;

import com.assistant.core.modules.sys.adapter.web.user.model.LoginCmd;
import com.assistant.core.modules.sys.adapter.web.user.model.UserInfo;
import com.assistant.core.modules.sys.app.user.cmd.UserInsertCmd;
import com.assistant.core.modules.sys.app.user.cmd.UserUpdateCmd;
import com.assistant.core.modules.sys.domain.user.JWTHelper;
import com.assistant.core.modules.sys.domain.user.Token;
import com.assistant.core.modules.sys.domain.user.User;
import com.assistant.core.modules.sys.app.user.UserService;
import com.assistant.util.MessageBodyWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping(value = "/sys")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private JWTHelper jwtHelper;

    @PostMapping(value = "/user/login")
    public MessageBodyWrapper<Map<String, String>> login(@RequestBody LoginCmd cmd) {
        User user = userService.login(cmd);
        final HashMap<String, String> result = new HashMap<>();
        result.put("token", jwtHelper.genToken(Token.fromUser(user)));
        return MessageBodyWrapper.success(result);
    }

    @PostMapping(value = "/user/logout")
    public MessageBodyWrapper<Object> logout() {
        return MessageBodyWrapper.success();
    }

    @GetMapping(value = "/user/info")
    public MessageBodyWrapper<UserInfo> info(User user) {
        return MessageBodyWrapper.success(UserInfo.createBy(user));
    }

    @GetMapping(value = "/user/{id}")
    public MessageBodyWrapper<UserInfo> get(@PathVariable("id") Long id) {
        return MessageBodyWrapper.success(UserInfo.createBy(userService.get(id)));
    }

    @GetMapping(value = "/users")
    public MessageBodyWrapper<List<UserInfo>> list() {
        return MessageBodyWrapper.success(userService.list().stream().map(UserInfo::createBy).collect(Collectors.toList()));
    }

    @PostMapping(value = "/user")
    public MessageBodyWrapper<Object> insert(@RequestBody @Validated UserInsertCmd cmd) {
        userService.insert(cmd);
        return MessageBodyWrapper.success();
    }

    @PutMapping(value = "/user/{id}")
    public MessageBodyWrapper<Object> update(@PathVariable("id") Long id, @RequestBody @Validated UserUpdateCmd cmd) {
        cmd.setId(id);
        userService.update(cmd);
        return MessageBodyWrapper.success();
    }

    @DeleteMapping(value = "/user/{id}")
    public MessageBodyWrapper<Object> update(@PathVariable("id") Long id) {
        userService.delete(id);
        return MessageBodyWrapper.success();
    }
}

